const { Customers } = require('../../schemas')
const { phoneRegex, encryptPhone } = require('../../utils/index.js')
const Snowflake = require('../../utils/snowflake.js')

const snowflake = new Snowflake(1, 1)

const customerCreated = async (request, reply) => {
  const { customerName, customerPhone, userName } = request.body
  try {
    // 请求体 校验
    if (!customerName || !customerPhone) {
      return reply.fail({
        code: 400,
        msg: '姓名/电话不能为空!',
      })
    }
    // 手机号校验
    if (!phoneRegex(customerPhone)) {
      return reply.fail({
        code: 400,
        msg: '手机号格式不正确！',
      })
    }
    // 防止重复提交
    const existingCustomer = await Customers.findOne({ customerPhone })

    if (existingCustomer) {
      return reply.fail({
        code: 409,
        msg: '客户已添加！',
      })
    }
    const customerId = snowflake.generateUserId(10)

    // 创建客户
    const customerData = new Customers({
      ...request.body,
      creator: userName,
      customerId,
      customerPhone,
      phoneRegex: encryptPhone(customerPhone),
    })

    await customerData.save()
    return reply.success({ msg: '添加成功！' })
  } catch (error) {
    return reply.fail({
      code: 500,
      msg: '服务器内部错误!',
      error: error.message,
    })
  }
}
const customerUpdated = async (request, reply) => {
  const { customerId, customerName, customerPhone, userName } = request.query
  try {
    if (!customerId) {
      return reply.fail({
        code: 400,
        msg: 'ID不能为空！',
      })
    }
    if (!customerName && !customerPhone) {
      return reply.fail({ code: 400, msg: '至少提供一项更新内容！' })
    }
    const customer = await Customers.findOne({ customerId })
    if (!customer) {
      return reply.fail({ code: 404, msg: '客户不存在！' })
    }
    if (customerPhone) {
      if (!phoneRegex(customerPhone)) {
        return reply.fail({ code: 400, msg: '手机号格式不正确！' })
      }
      const encryptedPhone = encryptPhone(customerPhone)
      if (encryptedPhone !== customer.customerPhone) {
        const phoneExists = await Customers.findOne({
          customerPhone: encryptedPhone,
        })
        if (phoneExists) {
          return reply.fail({ code: 409, msg: '手机号已被其他客户使用！' })
        }
        customer.customerPhone = encryptedPhone
      }
    }
    if (customerName) customer.customerName = customerName

    // 可添加其他字段更新逻辑
    customer.updater = userName // 记录更新人
    customer.updatedAt = new Date()

    await customer.save()

    return reply.success({ msg: '更新成功！' })
  } catch (error) {
    return reply.fail({
      code: 500,
      msg: '服务器内部错误!',
      error: error.message,
    })
  }
}
const customerDeleted = async (request, reply) => {
  const { customerId, userName } = request.query
  try {
    if (!customerId) {
      return reply.fail({
        code: 400,
        msg: 'ID不能为空！',
      })
    }
    const customer = await Customers.findOne({ customerId })
    if (!customer) {
      return reply.fail({ code: 404, msg: '客户不存在！' })
    }

    customer.deleted = true
    customer.deletedTime = new Date()
    customer.deleter = userName

    await customer.save()

    return reply.success({ msg: '删除成功！' })
  } catch (error) {
    return reply.fail({
      code: 500,
      msg: '服务器内部错误!',
      error: error.message,
    })
  }
}
const customerList = async (request, reply) => {
  try {
    const { currentPage = 1, currentSize = 10 } = request.query

    const page = parseInt(currentPage, 10)
    const size = parseInt(currentSize, 10)

    const skip = (page - 1) * size
    // 添加查询条件：排除 deleted=true 的客户
    const query = { deleted: { $ne: true } }

    const customer = await Customers.find(query, {
      _id: 0,
      __v: 0,
      deleted: 0,
      customerPhone: 0,
    })
      .sort({ createdAt: -1 }) // 按创建时间降序排序
      .skip(skip) // 跳过前面的记录
      .limit(size) // 限制返回的记录数

    const totalCustomers = await Customers.countDocuments(query)

    return reply.success({
      msg: '成功！',
      data: customer,
      currentPage: page,
      currentSize: size,
      total: totalCustomers,
      totalPages: Math.ceil(totalCustomers / size),
    })
  } catch (error) {
    return reply.fail({
      code: 500,
      msg: '服务器内部错误!',
      error: error.message,
    })
  }
}

module.exports = {
  customerCreated,
  customerUpdated,
  customerDeleted,
  customerList,
}
